package com.fwj.designpattern.singleton;

import java.util.concurrent.TimeUnit;

/**
 * Project Name: fwj
 * Author: fhw
 * File Name: LazySingleton  单例模式 - 懒汉模式
 * desc 只有使用的时候初始化，延迟加载。 1>保证线程安全 2>防止指令重拍 3>双重检测优化
 * Package Name: com.fwj.designpattern.singleton
 * Date: 2020/7/4 1:12 下午
 * Copyright (c) 2020,All Rights Reserved.
 */
public class LazySingleton {

    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                LazySingleton lazySingleton = LazySingleton.getInstance();
                System.out.println(lazySingleton);
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                LazySingleton lazySingleton = LazySingleton.getInstance();
                System.out.println(lazySingleton);
            }
        }).start();

    }

    private LazySingleton() {
    }

    private static LazySingleton instance;

    public static LazySingleton getInstance() {
        if (instance == null) {
            try {
                TimeUnit.MILLISECONDS.sleep(1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            synchronized (LazySingleton.class) {
                if (instance == null) {
                    instance = new LazySingleton();
                }
            }
        }
        return instance;
    }
}
